package cave.utils;

public class OrderedArray<T> {
	private Object[] array;
	private int maxItems, numItems;
	
	public OrderedArray() {
		this(10);
	}
	
	public OrderedArray(int capacity) {
		array = new Object[capacity];
		maxItems = capacity;
		numItems = 0;
	}
	
	@SuppressWarnings("unchecked")
	public T get(int index) {
		return (T)array[index];
	}
	
	public int add(T item) {
		if (numItems >= maxItems) {
			grow(maxItems * 2);
		}
		
		for (int i = 0; i < maxItems; ++i) {
			if (array[i] == null) {
				array[i] = item;
				numItems++;
				return i;
			}
		}
		
		return -1;
	}
	
	public void remove(int index) {
		array[index] = null;
		numItems--;
	}
	
	public void clear() {
		for (int i = 0; i < maxItems; ++i) {
			array[i] = null;
		}
		numItems = 0;
	}
	
	private void grow(int size) {
		Object[] newArray = new Object[size];
		System.arraycopy(array, 0, newArray, 0, numItems);
		array = newArray;
		maxItems = size;
	}
	
}
